package com.xuecheng.content.service.impl;

import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 异步上传课程发布的html页面
 *
 * @author 七安
 */
@Component
public class UploadHtml {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Async
    public void uploadHtml(Long coursePubId, Map<String, Object> map) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, TemplateException {
        //获取html页面
        Template template = configuration.getTemplate("learing_article.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //构建输入流
        ByteArrayInputStream input = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
        //上传后的文件名
        String htmlName = "/pages/" + coursePubId + ".html";
        minioClient.putObject(PutObjectArgs.builder()
                .contentType("text/html").object(htmlName)
                .bucket(minioProperties.getBucket())
                .stream(input, input.available(), -1)
                .build());
    }

    @Async
    public void deleteHtml(Long coursePubId) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String htmlName = "/pages/" + coursePubId + ".html";
        minioClient.removeObject("xuecheng", htmlName);
    }
}
